/**
* \file
* \author Adam Martin
* \date 2011-10-23
* \brief IrrlichtModule definitions.
*/

#include "IrrlichtRender.h"

// Standard Includes
#include <EngineConfig.h>

// Library Includes
#include <irrlicht\irrlicht.h>
using namespace irr;

// Local Includes
#include "../sharedbase/ModuleInterface.h"
#include "../sharedbase/EventLogger.h"
#include "../sharedbase/ModuleScriptInterface.h"
#include "../sharedbase/OSInterface.h"
#include "../enginecore/ScriptEngine.h"

// Static class member initialization
IrrlichtDevice* IrrlichtModule::device = 0;

// Class methods in the order they are defined within the class header

IrrlichtModule::IrrlichtModule( EventLogger* log ) : elog(log) {
	this->device = nullptr;
	this->smgr = nullptr;
	this->driver = nullptr;
}

void IrrlichtModule::Register( asIScriptEngine* const engine ) {
	int ret = 0;

	ret = engine->SetDefaultNamespace("Module::IrrlichtRender"); assert(ret >= 0);
	ret = engine->RegisterObjectType("IrrlichtRender", 0,  asOBJ_REF | asOBJ_NOHANDLE); assert( ret >= 0 );
	ret = engine->RegisterObjectMethod("IrrlichtRender", "bool StartDevice(int,int,string)", asMETHOD(IrrlichtModule, StartDevice), asCALL_THISCALL); assert( ret >= 0 );
	ret = engine->RegisterGlobalProperty("IrrlichtRender engine", this); assert( ret >= 0 );
	ret = engine->SetDefaultNamespace(""); assert(ret >= 0);
}

/**
* \param[in] dt Change in time in milliseconds since last update.
*/
void IrrlichtModule::Update( double dt ) {
	assert(this->driver != nullptr);
	this->driver->beginScene(true, true, video::SColor(255,100,101,140));

	this->smgr->drawAll();

	this->driver->endScene();
}

/**
* \param[in] width Width of the render window.
* \param[in] height Height of the render window.
* \param[in] title The title of the window when not fullscreen.
* \return True if the device was created successfully.
*/
bool IrrlichtModule::StartDevice( int width, int height, std::string title /*= ""*/ ) {
	this->device = createDevice(video::EDT_OPENGL, core::dimension2d<u32>(width, height), 32, false, false, false, nullptr);
	if (!this->device) {
		return false;
	}

	//device->setWindowCaption(title.c_str());

	this->smgr = this->device->getSceneManager();
	this->driver = this->device->getVideoDriver();
	return true;
}